package com.thunder.soft.ui.fragment;

import android.widget.Toast;

import androidx.lifecycle.Observer;
import androidx.recyclerview.widget.StaggeredGridLayoutManager;

import com.thunder.soft.R;
import com.thunder.soft.bean.ProjectBean;
import com.thunder.soft.common.base.BaseFragment;
import com.thunder.soft.common.util.ViewModelProviderHelper;
import com.thunder.soft.databinding.FragmentProjectBinding;
import com.thunder.soft.ui.adapter.ProjectDetailsAdapter;
import com.thunder.soft.vm.ProjectViewModel;

public class ProjectFragment extends BaseFragment<FragmentProjectBinding> {
    private ProjectViewModel projectViewModel;
    private ProjectDetailsAdapter projectDetailsAdapter;

    @Override
    protected void initData() {
        setTitleBar(binding.projectToolbar);

        projectViewModel = ViewModelProviderHelper.buildViewModel(this, ProjectViewModel.class);
        getLifecycle().addObserver(projectViewModel);

        projectDetailsAdapter = new ProjectDetailsAdapter();
        projectDetailsAdapter.setProjectViewModel(projectViewModel);

        StaggeredGridLayoutManager staggeredGridLayoutManager = new StaggeredGridLayoutManager(2,StaggeredGridLayoutManager.VERTICAL);
        binding.projectRecycler.setLayoutManager(staggeredGridLayoutManager);
        binding.projectRecycler.setAdapter(projectDetailsAdapter);

        binding.refreshLayout.autoRefresh();
        binding.refreshLayout.setOnRefreshListener(refresh -> projectViewModel.refreshData(true));
        binding.refreshLayout.setOnLoadMoreListener(refresh -> projectViewModel.refreshData(false));

        projectViewModel.getErrorMsg().observe(this, new Observer<String>() {
            @Override
            public void onChanged(String s) {
                Toast.makeText(getContext(), s, Toast.LENGTH_SHORT).show();
            }
        });

        projectViewModel.getProjectLiveData().observe(this, new Observer<ProjectBean>() {
            @Override
            public void onChanged(ProjectBean projectBeans) {
                if (projectBeans.getDatas().size() < 20) {
                    binding.refreshLayout.finishLoadMoreWithNoMoreData();
                }
                if (projectBeans.getCurPage() == 1) {
                    binding.refreshLayout.finishRefresh();
                    projectDetailsAdapter.addListClear(projectBeans.getDatas());
                } else {
                    projectDetailsAdapter.addList(projectBeans.getDatas());
                    binding.refreshLayout.finishLoadMore();
                }
            }
        });
    }

    @Override
    protected int layoutId() {
        return R.layout.fragment_project;
    }
}